import { userBehavior } from "@/behaviors/userBehavior";

import { debounce } from "miniprogram-licia";

import {
  reqCartList,
  reqCartState,
  reqCartChecked,
  reqCartAdd,
  reqCartDel,
} from "@/api/cart";
const computedBehavior = require("miniprogram-computed").behavior;

Component({
  // 组件的属性列表
  properties: {},
  behaviors: [userBehavior, computedBehavior],
  // 组件的初始数据
  data: {
    cartList: [],
    emptyDes: "还没有添加商品，快去添加吧～",
    loginFlag: true, // 是否登录 true 代表登录；false 代表未登录
  },
  methods: {
    // 获取购物车列表
    async getCartList() {
      const { data } = await reqCartList();
      this.setData({
        cartList: data.data,
      });
    },

    // 删除购物车列表
    cartDel(event) {
      const _this = this;
      wx.showModal({
        content: "您确定删除该商品吗？",
        async success(res) {
          if (res.confirm) {
            const { data } = await reqCartDel({
              goodsId: event.currentTarget.dataset.id,
            });
            if (data.code === 200) {
              // wx.showToast({ title: "删除成功!", icon: "none" });
              _this.getCartList();
            }
          }
        },
      });
    },

    // 更新商品购买数量
    countChange: debounce(async function (event) {
      console.log("更新商品购买数量=》", event);
      const { id, index, countold } = event.currentTarget.dataset;
      const countNew = event.detail;
      const difference = countNew - countold; // 差值

      if (countNew === 0) return; // 说明商品数量没有发生改变

      const { data } = await reqCartAdd({ goodsId: id, count: difference });
      if (data.code === 200) {
        this.setData({
          [`cartList[${index}].count`]: countNew,
          [`cartList[${index}].isChecked`]: 1,
        });
      }
    }, 500),

    // 更新商品购买状态
    async checkboxClick(event) {
      // console.log("更新商品购买状态=》", event);
      const { goodsid, index } = event.currentTarget.dataset;
      const goodsId = goodsid;
      const isChecked = index ? 0 : 1;
      const { data } = await reqCartState({ goodsId, isChecked });
      if (data.code === 200) {
        this.getCartList();
      }
    },

    // 全选按钮
    async onChange(event) {
      console.log("全选按钮=》", event);
      const isChecked = event.detail ? 1 : 0;
      const { data } = await reqCartChecked({ isChecked });
      if (data.code === 200) {
        this.getCartList();
      }
    },

    // 去结算
    onSubmit() {
      if (this.data.totalPrice === 0) {
        wx.showToast({ title: "请选择需要购买的商品", icon: "none" });
        return;
      }
      wx.navigateTo({
        url: `/modules/orderPayModule/pages/order/detail/detail`,
      });
    },

    onShow() {
      if (!this.data.token) {
        this.setData({
          loginFlag: false,
          emptyDes: "您尚未登录，点击登录获取更多权益",
          cartList: [],
        });
      } else {
        this.setData({
          loginFlag: true,
          emptyDes: "还没有添加商品，快去添加吧～",
        });

        this.getCartList();
      }
    },
  },

  computed: {
    // 判断是否全选
    allChecked(data) {
      return (
        data.cartList.length > 0 &&
        data.cartList.every((item) => item.isChecked === 1)
      );
    },
    // 总金额
    totalPrice(data) {
      let totalSum = 0;
      data.cartList.forEach((item) => {
        if (item.isChecked) {
          totalSum += item.price * item.count;
        }
      });

      return totalSum * 100;
    },
  },
});
